package cn.yi.fast.security.shiro;

import cn.yi.fast.security.response.R;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Splitter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.List;

public class UserSessionFilter extends UserFilter {

    /**
     * 忽略的url
     */
    @Setter
    private String ignoreUrls;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object o)  {
        if(isIgnoreRequest(request)){
            return true;
        }
        return super.isAccessAllowed(request,response,o);
    }



    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        saveRequest(request);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(requestNeedLoginInfo()));
        return false;
    }

    /**
     * 判断是否需要忽略登陆
     * @param request
     * @return
     */
    private boolean isIgnoreRequest(ServletRequest request) {
        boolean isIgnoreRequest = false;
        if(StringUtils.isNotBlank(ignoreUrls)){
            List<String> ignoreUrlList = Splitter.on(",").splitToList(ignoreUrls);
            for (String ignoreUrl : ignoreUrlList) {
                isIgnoreRequest = pathsMatch(ignoreUrl,request);

            }
        }
        return isIgnoreRequest;
    }
    private R requestNeedLoginInfo() {
        return R.error("请先登录");
    }
}
